<?php
require_once('../../libraryfiles/config.php');


$action = isset($_GET['action']) ? $_GET['action'] : '';

switch ($action) {
    case 'add' :
        add();
        break;

    case 'apply' :
        add(true);

    case 'addexist' :
        addexist();
        break;

    case 'delselected' :
        deleteSelected();
        break;

    case 'deletet_count' :
        deletetCount();
        break;

    case 'multiDelete' :
        deleteProduct();
        break;

    case 'publish' :
        publishSelected();
        break;

    case 'updatePrice':
        updatePrice();
        break;

    case 'displaypro':
        display();
        break;

    case 'diplayexist':
        displayexit();
        break;

    case 'search_pro':
        search_pro();
        break;

    default :
        // if action is not defined or unknown
        // move to main user page
        header('Location: index.php');
        exit();
}

function add() {
    $ID = $_POST['hidid'];
    $pro_name = ampReplace($_POST['new_proname']);
    $pro_name = addslashes($pro_name);
    $pro_typ = @$_POST['selectType'];
    $pro_version = trim($_POST['selectProductVersion']);
    $pro_keywords = trim($_POST['txtkeywords']);
    $made_in = @$_POST['selectCoun'];
    $pro_price = $_POST['price'];
    $laboratory = @$_POST['laboratory'];
    $pharmacy_id = @$_SESSION['acc_id'];
    $pid = @$_POST['hidpid'];
    $desc = str_replace("'", "'", $_POST['txtdesc']);
    $desc = str_replace("\"../images/", "\"" . W_IMAGES_DIR, $desc);
    $desc = str_replace("\"../../images/", "\"" . W_IMAGES_DIR, $desc);
    $desc = addslashes($desc);
    $link = $detectExist_q = "";

    $Cont_Name = trim($_POST['txtname']);
    $Cont_Email = trim($_POST['txtemail']);
    $Cont_Tel = trim($_POST['txttelephone']);
    $Cont_Address = trim($_POST['txtaddress']);

    if (empty($ID)) {
        if (empty($_POST['new_proname']) || empty($_POST['txtdesc']) || empty($_POST['price']) || empty($_POST['selectcat']) || empty($_POST['txtname']) || empty($_POST['txtemail']) || empty($_POST['txttelephone']) || empty($_POST['txtaddress'])) {
            header("location:" . base_url_admin . "/product/index.php?view=add&error=required");
            exit();
        }
    }
    $modify = false;
    if (!empty($ID)) {
        $detectExist_q = '';
        $modify = true;
        $link = "&id=" . $ID;
        $detectExist_q .= " AND id != " . $ID;
    }

    //Statment to detect the entry Lesson Category Name exist
    if (existRecord("tblproduct", "product_name = '$pro_name' $detectExist_q")) {
        header('Location:' . base_url_admin . '/product/index.php?view=add' . $link . $qstr . '&error=' . urlencode('Name already taken. Please choose another one'));
        exit();
    } else if ($modify) {
        //Statement to update the lesson category info
        $update_q = "UPDATE tblproduct
					 SET product_name = '" . $pro_name . "', product_description = '" . $desc . "',product_keyword='" . $pro_keywords . "',product_version='" . $pro_version . "',contact_name='" . $Cont_Name . "',contact_email='" . $Cont_Email . "',contact_phone='" . $Cont_Tel . "',contact_address='" . $Cont_Address . "', mdate = NOW(), product_type = '" . $pro_typ . "', owner = '" . $pharmacy_id . "'  WHERE id ='" . $ID . "'";
        $last_id = $ID;
        mysql_query($update_q);

        $sql2 = "DELETE FROM tblproduct_in_category WHERE product_id = '" . $last_id . "'";
        mysql_query($sql2);
        //Pharmacy Query
        foreach ($made_in as $key => $value) {

            $country = $value;
            $price = $pro_price[$key];
            $pro_reg_price = @$pro_reg_price[$key];
            $labor = @$laboratory[$key];
            $sql_del = "DELETE FROM tblproduct_in_pharmacy WHERE product_id='" . @$ID . "'";
            mysql_query($sql_del);
            $sql_pha = "INSERT INTO tblproduct_in_pharmacy(product_id, pharmacy_id, country_id, regular_price, price, laboratory, status) VALUES($last_id, $pharmacy_id, $country, '$pro_reg_price', '$price', '$labor',1)";
            mysql_query($sql_pha);
        }
    } else {
        //Ordering number
        $ordering_q = "SELECT MAX(product_ordering) AS ordering
				   FROM tblproduct";
        $ordering_r = mysql_query($ordering_q);
        $ordering_info = dbFetchAssoc($ordering_r);
        extract($ordering_info);
        $ordering += 1;
        // Product Query
        $province_id = isset($_SESSION['province_id']) ? $_SESSION['province_id'] : "";
        $district_id = isset($_SESSION['disctict_id']) ? $_SESSION['disctict_id'] : "";
        $postType = (($_SESSION['usertype'] == 2) ? 1 : 0);
        $insert_q = "INSERT INTO tblproduct(product_name, product_type, product_version, product_keyword, product_ordering, cdate, mdate, product_description, status, owner,pr_province_id,pr_district_id, post_type,contact_name,contact_email,contact_phone,contact_address) VALUES('" . $pro_name . "', '" . $pro_typ . "', '" . $pro_version . "', '" . $pro_keywords . "', '" . $ordering . "', NOW(), NOW(), '" . trim($desc) . "', 1,'" . $pharmacy_id . "','" . $province_id . "','" . $district_id . "','" . $postType . "','" . $Cont_Name . "','" . $Cont_Email . "','" . $Cont_Tel . "','" . $Cont_Address . "')";
        mysql_query($insert_q);

        $last_id = mysql_insert_id();

        //Pharmacy Query
        foreach ($made_in as $key => $value) {
            $country = $value;
            $price = $pro_price[$key];
            $labor = $laboratory[$key];
            $sql_pha = "INSERT INTO tblproduct_in_pharmacy(product_id, pharmacy_id, country_id, price, laboratory, status) VALUES('" . $last_id . "', '" . $pharmacy_id . "', '" . $country . "', '" . $price . "', '" . $labor . "',1)";
            mysql_query($sql_pha);
        }
    }

    // Category Query
    $selectCate = array();
    $selectCate = isset($_POST['selectcat']) ? $_POST['selectcat'] : '';
    foreach ($selectCate as $value) {

        $sql_cate = "INSERT INTO tblproduct_in_category VALUES('" . $value . "','" . $last_id . "')";
        mysql_query($sql_cate);
    }


    // Insert Image
    $imagefile = $_FILES['imagefile'];
    if(!empty($imagefile)){
    $arrayTemp = array();
    foreach ($imagefile as $index => $name) {
        foreach ($name as $key => $value) {
            $arrayTemp[$key][$index] = $value;
        }
    }
    }
    include S_ROOT . '/includefiles/upload_image_options.php';
    if (!empty($ID)) {
        if (!empty($_POST['DelImage'])) {
            $images_id = $_POST['DelImage'];
            foreach ($images_id as $image_id) {
                $imgName = mysql_query("SELECT *FROM tblimage WHERE id='" . $image_id . "'");
                $img = mysql_fetch_object($imgName);
                if (!empty($img)) {
                    $fullImage = S_S_IMAGES_DIR . 'thumb/' . $img->images;
                    $thumbImage = S_S_IMAGES_DIR . $img->images;
                    if (file_exists($thumbImage)) {
                        unlink($fullImage);
                        unlink($thumbImage);
                    }
                    $deleteImgQuery = "DELETE FROM tblimage WHERE id='" . $img->id . "'";
                    mysql_query($deleteImgQuery);
                }
            }
        }
        
         if (!empty($arrayTemp)) {
            foreach ($arrayTemp as $newimage) {
                if (!empty($newimage['name'])) {
                    $imageName = uploadProductimage($newimage, $resizeWidth, $resizeHeight, $logoPath, $logoPosition);
                    if (!empty($imageName)) {
                        /* insert to DB */
                        $data_img = array(
                            Tblimage::images => $imageName,
                            Tblimage::product_id => $last_id,
                        );
                        $imageInsert = insert(Tblimage::TABLE, $data_img);
                    }
                }
                /* end insert to DB */
                /* end upload with resize and watermark */
            }
        }
    } else {
        if (!empty($arrayTemp)) {
            foreach ($arrayTemp as $newimage) {
                if (!empty($newimage['name'])) {
                    $imageName = uploadProductimage($newimage, $resizeWidth, $resizeHeight, $logoPath, $logoPosition);
                  
                    if (!empty($imageName)) {
                        /* insert to DB */
                        $data_img = array(
                            Tblimage::images => $imageName,
                            Tblimage::product_id => $last_id,
                        );
                        $imageInsert = insert(Tblimage::TABLE, $data_img);
                    }
                }
                /* end insert to DB */
                /* end upload with resize and watermark */
            }
            
        }
    }
    header('Location:' . base_url_admin . '/product/index.php?msg=add');
}

function addexist() {
    $id = $_POST['hidnewid'];
    $made_in = $_POST['selectCountry'];
    $pro_price = $_POST['newprice'];
    $pharmacy_id = $_SESSION['acc_id'];
    $laboratory = $_POST['new_laboratory'];
    $pid = $_POST['hidupdate'];
    $link = $detectExist_q = "";
    $modify = false;
    if (!empty($pid)) {
        $modify = true;
        $link = "&id=" . $pid;
        $detectExist_q .= " AND pid != " . $pid;
    }
    // exist record
    foreach ($made_in as $key => $value) {
        $country = $value;
        $price = $pro_price[$key];
        $labor = addslashes($laboratory[$key]);
        $pids = $pid[$key];
        $sql_e = "SELECT * FROM tblproduct_in_pharmacy WHERE product_id = $id AND country_id = $country AND pharmacy_id = $pharmacy_id AND laboratory = '$labor' AND pid!=$pids";
        $result_e = mysql_query($sql_e);
    }
    if (dbNumRows($result_e)) {
        $error = 'You have this product already !';
        header("Location:" . base_url_admin . "/product/index.php?view=add&errorexist=$error");
        exit();
    } else if ($modify) {
        foreach ($made_in as $key => $value) {
            $country = $value;
            $price = $pro_price[$key];
            $labor = addslashes($laboratory[$key]);
            $pids = $pid[$key];
            $sql_del = "DELETE FROM tblproduct_in_pharmacy WHERE product_id=$pids";
            mysql_query($sql_del);
            $sql_pha = "INSERT INTO tblproduct_in_pharmacy(product_id, pharmacy_id, country_id, price, laboratory, status) VALUES($id, '$pharmacy_id', '$country', '$price', '$labor',1)";
            mysql_query($sql_pha);
        }
    } else {
        //Pharmacy Query
        foreach ($made_in as $key => $value) {
            $country = $value;
            $price = $pro_price[$key];
            $labor = $laboratory[$key];
            $sql_pha = "INSERT INTO tblproduct_in_pharmacy(product_id, pharmacy_id, country_id, price, laboratory, status) VALUES($id, '$pharmacy_id', '$country', '$price', '$labor',1)";
            mysql_query($sql_pha);
        }
    }
    header("Location:" . base_url_admin . "/product/index.php");
    exit();
}

function search_highlight($needle, $replace, $haystack) {
    $haystack = str_replace($needle, $replace, $haystack);
    return $haystack;
}

function search_pro() {
    $pro_name = addslashes($_GET['searchword']);
    $sql = "SELECT * FROM tblproduct WHERE product_name LIKE '$pro_name%' AND status = 1";
    $result = mysql_query($sql);
    if (dbNumRows($result)) {
        echo '<span id="id" style="color:#999;"><em>Search Result...</em></span><br /><br />';
        $i = 1;
        while ($row = dbFetchAssoc($result)) {
            $sql_img = "SELECT thumbnail FROM tblimage WHERE product_id = " . $row['id'] . " LIMIT 0,1";
            $result_img = mysql_query($sql_img);
            $row_img = dbFetchAssoc($result_img);
            if ($i % 2) {
                $class = 'search_row1';
            } else {
                $class = 'search_row2';
            }
            $i++;
            ?>
            <div style="width: 320px; height: auto;">
                <div style="float: left; width: 70px;"><?php
            if ($row_img['thumbnail'] != "") {
                $thumbnail_i = $row_img['thumbnail'];
            } else {
                $thumbnail_i = 'no-image-small.png';
            }
            ?> <img
                        src="<?php echo W_ROOT; ?>../../product/images/<?php echo $thumbnail_i; ?>"
                        class="border" width="70" /></div>
                <div
                    style="float: left; padding-left: 15px; padding-top: 10px; width: 180px;"><strong
                        style="color: #06C;"><?php echo $row['product_name']; ?></strong><br />
                    <em style="color: #666;">( Product type : <?php echo $row['product_type']; ?>
                        )</em></div>
                <div style="float: right; padding-top: 10px;"><a href="#1"
                                                                 id="<?php echo $row['id']; ?>" class="addproduct"><img
                            src="<?php echo W_ROOT; ?>/images/btnadd.jpg" border="0" /></a></div>
            </div>
            <div
                style="clear: both; height: 5px;"></div>
                <?php
            }// end while
            ?>
        <br />
        <img
            src="<?php echo W_ROOT; ?>/images/add_icon.jpg" border="0" />
        <a style="color: #00F; text-decoration: underline; cursor: pointer;"
           id="clicktoadd" onclick="$('#formaddnew').show();"><em>Add New Product</em></a>
           <?php
       } else {
           ?>
        <span id="id" style="color: #999;"><em>No Result Found !....</em></span>
        &nbsp;&nbsp;
        <img
            src="<?php echo W_ROOT; ?>/images/add_icon.jpg" border="0" />
        <a
            style="color: #00F; text-decoration: underline; cursor: pointer; width: 547px;"
            id="clicktoadd" onclick="$('#formaddnew').show();" title="Add New"><em>Add
                New Product</em></a>
        <br />
        <br />
        <br />
        <?php
    }
}

function displayexit() {
    $id = isset($_GET['id']) ? $_GET['id'] : '';
    $exist = 1;
    include(S_ROOT . '/admin/product/formaddexist.php');
    exit;
}

function display() {
    $id = $_GET['id'];
    $sql = "SELECT * FROM tblcategory WHERE parent_id = $id";
    $result = mysql_query($sql);
    ?>
    <br />
    <?php
    while ($row = dbFetchassoc($result)) {
        ?>
        <option value="<?php echo $row['id']; ?>"><?php echo $row['category_name']; ?></option>
        <?php
    }
}

function updatePrice() {
    $pro_id = $_POST['hidepid'];
    foreach ($pro_id as $value) {
        $price = $_POST['price' . $value];
        $sql_price = "UPDATE tblproduct_in_pharmacy SET price = '$price' WHERE pid = $value";
        mysql_query($sql_price);
    }
    header('Location: ' . W_ROOT . '/account/editProductPrice.php?updatesuccess=1');
    exit();
}

function publishSelected() {
    if (isset($_POST['id'])) {
        if (isset($_GET['publish']) && (int) $_GET['publish'] >= 0 && (int) $_GET['publish'] <= 1) {
            $publish = (int) $_GET['publish'];
        } else {
            header('Location: index.php');
            exit();
        }

        if (isset($_GET['pharm_id']) && (int) $_GET['pharm_id'] >= 0) {
            $phar_id = (int) $_GET['pharm_id'];
        }

        //Statement to get selected id
        $id = (is_array($_POST['id'])) ? implode(',', $_POST['id']) : $_POST['id'];

        //Statement to publish/unpublish selected id
        publishPro('tblproduct_in_pharmacy', $publish, $id, $phar_id);
    }

    header('Location: index.php?' . getAllGetParams(array('view', 'action', 'publish')));
    exit();
}

function deleteSelected() {
    if (isset($_POST['id'])) {
        //Statement to get selected id
        $id = (is_array($_POST['id'])) ? implode(',', $_POST['id']) : $_POST['id'];
        $selec_delet = "SELECT *FROM tblproduct AS pro INNER JOIN tblimage AS im ON pro.id=im.product_id WHERE product_id IN($id)";
        $run_query = mysql_query($selec_delet);
        //Statment to delete selected id
        $sql = "DELETE FROM tblproduct WHERE id IN ($id)";
        mysql_query($sql);
        if (mysql_num_rows($run_query) > 0) {
            while ($rows = mysql_fetch_array($run_query)) {
                $product_image = $rows['images'];
                if(file_exists(S_S_IMAGES_DIR .$product_image)){
                    unlink(S_S_IMAGES_DIR .$product_image );
                    unlink(S_S_IMAGES_DIR.'thumb/'. $product_image);
                }
            }
        }
    }
    header('Location: ' . $_SESSION['shop_return_url']);
}

// end deleteSelected

function deletetCount() {
    $pid = $_GET['pid'];
    $selec_delet = "SELECT *FROM tblproduct AS pro INNER JOIN tblimage AS im ON pro.id=im.product_id WHERE product_id IN($pid)";
    $run_query = mysql_query($selec_delet);
    $sql = "DELETE FROM tblproduct_in_pharmacy WHERE pid = $pid";
    mysql_query($sql);
    $imagePath = '/product/images/';
    if (mysql_num_rows($run_query) > 0) {
        while ($rows = mysql_fetch_array($run_query)) {
            $product_image = $rows['images'];
            if (file_exists(S_S_IMAGES_DIR.$product_image)) {
                unlink(S_S_IMAGES_DIR.'thumb/'.$product_image);
            }
            if (file_exists(S_S_IMAGES_DIR.$product_image)) {
                unlink(S_S_IMAGES_DIR.$product_image);
            }
        }
    }
    exit();
}

/*
 * Remove Product
 */

function deleteProduct() {
    if (isset($_POST['id'])) {
        $ids = (is_array($_POST ['id'])) ? implode(',', $_POST ['id']) : $_POST ['id'];
        $sql_image = mysql_query("SELECT * FROM tblimage WHERE product_id IN($ids)");
        while ($imgLinks = mysql_fetch_object($sql_image)) {
            if (file_exists(S_ROOT . '/product/images/' . $imgLinks->images)) {
                unlink(S_ROOT . '/product/images/' . $imgLinks->images);
            }
            if (file_exists(S_ROOT . '/product/images/thumb/' . $imgLinks->images)) {
                unlink(S_ROOT . '/product/images/thumb/' . $imgLinks->images);
            }
        }
        $sql = "DELETE FROM tblproduct WHERE id IN ($ids)";
        mysql_query("DELETE FROM tblimage WHERE product_id IN($ids)");
        mysql_query("DELETE FROM tblproduct_in_pharmacy WHERE product_id IN($ids)");
        mysql_query($sql);
        header('Location: ' . $_SESSION ['shop_return_url']);
        exit();
    }
}



function muliDelete() {
    if (isset($_POST['id'])) {

        //Statement to get selected id
        $id = (is_array($_POST['id'])) ? implode(',', $_POST['id']) : $_POST['id'];
        //Statment to delete selected id

        $image = '';
        $add_img = 'upload_image/';
        $img = mysql_query("SELECT *FROM tblproduct WHERE id=" . $id);
        while ($arr = mysql_fetch_array($img)) {
            $image = $arr['adv_upload_image'];
            unlink($add_img . "banner/" . $image);
        }

        $sql = "DELETE FROM tblproduct WHERE id IN ($id)";
        mysql_query($sql);
    }
    header('Location:' . base_url_admin . '/product/index.php');
    exit();
}
?>
